/********************************************************************
 * Filename:	LRU.c
 * Description: Least recently used algorithm.
 * Group 2:		nachOS
 * Author(s):	Daniel Fairweather
 *				Ying Wang
 *				Jan Durakiewicz
 * Class:		CSE 325
 * Instructor:	David Duggan
 * Assignment:	Lab #6 Page Replacement
 * Assigned:	4/2/2013
 * Due:			4/9/2013
 ********************************************************************/
#include "LRU.h"

Linked_List_Node nodes[200];
Linked_List_Node* head = 0;
Linked_List_Node* tail = 0;
int numNodes = 0;

void init_LRU(){
	int i;

	nodes[0].previous = 0;
	nodes[0].next = &nodes[1];
	nodes[0].value = 199;

	for(i = 1; i < 199; i++){
		nodes[i].previous = &nodes[i-1];
		nodes[i].next = &nodes[i+1];
		nodes[i].value = 199 - i;
	}

	nodes[199].previous = &nodes[198];
	nodes[199].next = 0;
	nodes[199].value = 0;

	head = &nodes[0];
	tail = &nodes[199];
	numNodes = 0;
}

void accessNode(int nodeID){

	Linked_List_Node* node = &nodes[nodeID];

	/* If the item is already at the head, do nothing. */
	if(node == head){
		return;
	}

	/* If the item is at the tail, do something else. */
	else if(node == tail){
		nodeFault();
	}

	else{
		node->previous->next = node->next;
		node->next->previous = node->previous;
		node->next = head;
		node->previous = 0;
		head->previous = node;
		head = node;
	}
}


int nodeFault(){
	Linked_List_Node* node = tail;

	node->previous->next = node->next;
	tail = node->previous;
	node->next = head;
	node->previous = 0;
	head->previous = node;
	head = node;

	if(numNodes != 200){
		numNodes++;
	}

	return(node->value);
}